/*
 * Part of the NXT bluetooth remote control J2ME applet.
 * Copyright (C) 2007-2008 Alexander Demin, <alexander@demin.ws>
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You can redistribute this file and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your discretion) any later version.
 * See the accompanying file "COPYING.txt" for more details.
 */
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

public class NxtMidlet extends MIDlet implements CommandListener {

    private Command exitCommand = new Command("Exit", Command.ITEM, 10);
    private Command connectCommand = new Command("Connect", Command.BACK, 10);
    
    private Form mainForm;

    private NxtBrick nxtBrick;

    public class Logger {

       NxtMidlet owner;

       public Logger(NxtMidlet aOwner) {
          owner = aOwner;
       }

       public void line( String s ) {
          owner.mainForm.append( s + "\n" );
       }
    }

    private Logger logger;

    public NxtMidlet() {

        logger = new Logger(this);

        mainForm = new Form("NXT Remote Control v1.1");

        mainForm.addCommand(exitCommand);
        mainForm.addCommand(connectCommand);

        mainForm.setCommandListener(this);

        nxtBrick = new NxtBrick(logger);

        logger.line( "Started" );
    }
    
    protected void startApp() {
        Display.getDisplay(this).setCurrent(mainForm);
    }
    
    public void commandAction(Command c, Displayable s) {
	if (c == exitCommand) {
	    destroyApp(false);
	    notifyDestroyed();
	}

	if (c == connectCommand) {

           mainForm.removeCommand(connectCommand);

           mainForm.deleteAll();

           final Display d = Display.getDisplay(this);

	   Thread connector = new Thread() {
	      public void run() {
                 try {
                    logger.line( "Connecting..." );
                    nxtBrick.connect();
                    logger.line( "Connected" );

                    d.setCurrent( new NxtCanvas(nxtBrick) );
    
                 } catch( Exception e ) {
                    logger.line( e.getMessage() );
                    logger.line( "Try again" );
                    mainForm.addCommand(connectCommand);
                 }
              }
           };

           connector.start();
        }
    }
    
    protected void destroyApp(boolean unconditional) {
    }
    
    protected void pauseApp() {
    }
}
